//go:build !edge
// +build !edge

package protocol

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"iot-base/common/cache"
	"iot-base/common/notify"
	"iot-base/devc/common/jsonrpc"
	"net/http"
	"strings"
)

func HandleRequest(w http.ResponseWriter, r *http.Request) {
	body, _ := ioutil.ReadAll(r.Body)
	defer r.Body.Close()
	body_str := string(body)
	fmt.Println("body-------------", body_str)
	//    fmt.Fprint(w, body_str)
	var rpc jsonrpc.JSONRPCRequest
	//rpc.Params = make(map[string]interface{})
	if err := json.Unmarshal(body, &rpc); err == nil {
		if rpc.Params != nil {
			params := rpc.Params.(map[string]interface{})
			if params != nil {
				token := params["token"]
				if token != nil {

					stoken := token.(string)
					url, _ := base64.StdEncoding.DecodeString(stoken)
					surl := string(url)
					parts := strings.Split(surl, "/")
					plen := len(parts)
					if plen > 2 {
						tid := parts[plen-2]
						vtoken := parts[plen-1]
						fmt.Println("tokens---------", tid, vtoken)
						info, err := cache.GetVideoAddr(tid)
						if info != nil && err == nil {
							for _, option := range info.StreamOptions {
								//if option != nil {
								if option.Name == vtoken {
									params = make(map[string]interface{}, 2)

									urlPos := strings.Index(surl, "url:")
									//tokenPos := strings.Index(surl, "?token")
									if urlPos >= 0 {
										pushurl := surl[urlPos+4:]
										params["pushurl"] = pushurl
										params["srcurl"] = tid + ":::" + vtoken
										fmt.Println("tokens---------", params, "url", pushurl)
										pThing, _ := cache.GetThing(tid)
										if pThing != nil {
											edgeID := pThing.Thing.ProxyThingID
											if edgeID != "" {
												errc := notify.CtrlThing(edgeID, "doRTSPPush", 0, params, nil, false)
												if errc != nil {
													fmt.Println("--------------errorc----", errc)
												}
												fmt.Println("send ctrl cmd---------------!!!!!")
												fmt.Fprint(w, `{"jsonrpc":"2.0","method":"","result":"success"}`)
												return
											}
										}

									}
									break
								}
								//}
							}
						}
					} else {
						fmt.Println("-------------------token len", plen)
					}
				} else {
					fmt.Println("-------------------token is null", params)
				}
			} else {
				fmt.Println("-------------------params is null")
			}
		} else {
			fmt.Println("-------------------rpc param is null")
		}
	}
	fmt.Fprint(w, `{"jsonrpc":"2.0","method":"","error":{"code":-1,"message":"not found"}}`)
}
func init() {
	http.HandleFunc("/manage/simulator/media/cmd", HandleRequest)
	go http.ListenAndServe(":20000", nil)
}
